<template>
  <div id="personal_info">
    <div class="info_title">基本资料</div>
    <div class="line"></div>
    <div class="info_user">账号信息</div>
    <div class="info_user_name">
      用户名
      <span>{{personal_info.username}}</span>
    </div>
    <el-link @click="gotoChange()" class="changePWD" type="success">修改密码</el-link>
    <div class="line"></div>
    <div class="info_user">孩子信息</div>
    <el-form
      ref="form"
      label-width="80px"
      class="ruleForm"
      label-position="left"
      :model="personal_info"
    >
      <el-form-item label="孩子姓名" style="margin-bottom: 0.06rem;">
        <el-input
          ref="nickName"
          v-model="personal_info.clueEntity.realName"
          clearable
          maxlength="10"
          style="width:28%"
          placeholder="请输入姓名"
        ></el-input>
      </el-form-item>
      <el-form-item label="性别" style="margin-bottom: 0.05rem;">
        <el-radio-group ref="gender" v-model="personal_info.clueEntity.gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="头像">
        <div class="stuheadimgbox">
          <div class="headimg">
            <img
              alt="图片加载失败"
              onerror="this.src='require('../../assets/img/person/default_photo.png')';this.onerror=null"
              :src="personal_info.photo == ('' || null)?defaultImg:personal_info.photo"
            >
            <!-- <img :src="defaultImg"> -->
            <!-- <img src="../../assets/img/person/default_photo.png"> -->
          </div>
          <div class="uploadimg">
            <el-upload
              ref="photo"
              :action="uploadUrl"
              :data="uploadData"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="headers"
              :on-error="uploadError"
              accept=".jpg, .png"
            >
              <el-button type="primary">上传照片</el-button>
            </el-upload>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="出生年月">
        <el-date-picker
          ref="birthday"
          style="width:28%"
          @change="changDate"
          v-model="personal_info.clueEntity.birthday"
          type="month"
          value-format="yyyy-MM"
          placeholder="请选择出生年月"
        ></el-date-picker>
        <!-- <el-date-picker
          ref="birthday"
          
          v-model="personal_info.clueEntity.birthday"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="请选择年月日"
        ></el-date-picker>-->
      </el-form-item>
      <el-form-item label="学校">
        <el-input
          ref="kindergarten"
          clearable
          v-model="personal_info.clueEntity.kindergarten"
          maxlength="10"
          style="width:28%"
          placeholder="请输入学校名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="年级">
        <el-select
          style="width:28%"
          ref="grade"
          clearable
          v-model="personal_info.clueEntity.grade"
          placeholder="请选择年级"
        >
          <el-option
            v-for="item in gradeList"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="收货地址">
        <div v-if="personal_info.studentUserAddressEntityList.length == 0">
          <span class="add_btn" @click="addAdress()"></span>
        </div>
        <div v-for="item,index in personal_info.studentUserAddressEntityList">
          <div class="line1" v-if="index >0"></div>
          <el-input
            :ref="item.receiverName"
            clearable
            v-model="item.receiverName"
            maxlength="10"
            style="width:28%"
            placeholder="收件人姓名"
          ></el-input>
          <el-input
            :ref="item.receiverPhone"
            clearable
            v-model="item.receiverPhone"
            maxlength="11"
            oninput="value=value.replace(/[^\d]/g,'')"
            style="width:28%;margin-left:0.03rem;"
            placeholder="收件人手机号"
          ></el-input>
          <el-cascader
            style="width:57%;margin-top:0.1rem;"
            v-model="item.citys"
            clearable
            :props="defaultProps"
            :options="citys"
            placeholder="请选择所在地区"
          ></el-cascader>

          <el-input
            :ref="item.address"
            v-model="item.address"
            clearable
            maxlength="50"
            style="width:57%;margin-top:0.1rem;"
            placeholder="请输入详细地址"
          ></el-input>
          <span class="add_btn" @click="addAdress()"></span>
          <span class="reduce_btn" @click="reduceAdress(item)"></span>
          <el-checkbox
            style="width:57%;"
            @change="checkChange(item)"
            v-model="item.isUse == '1'"
          >默认为常用收货地址</el-checkbox>
        </div>
      </el-form-item>
    </el-form>
    <div class="footer">
      <el-button
        type="primary"
        @click="submit()"
        style="border-radius: 0.08rem;width: 1.62rem;font-size:0.16rem;padding: 0.11rem 0.2rem;margin-bottom:0.2rem;"
      >保 存</el-button>
    </div>
  </div>
</template>

<script>
import citys from "../../../static/json/citys.json";
let vm;
export default {
  data: function() {
    return {
      isFirstAdd: false,
      //默认头像
      defaultImg: require("../../assets/img/person/default_photo.png"),
      //上传地址
      uploadUrl: window.config.baseUrl + "file/upload",
      //请求头部信息
      headers: {
        // 'Content-Type': 'multipart/form-data',
        token: tool.getItem(lsKey.token, true)[0]
      },
      //上传额外参数
      uploadData: {
        content: "studentlogo"
      },
      gradeList: [],
      defaultProps: {
        label: "label",
        value: "label",
        children: "children"
      },
      citys: [],
      personal_info: {
        clueEntity: {},
      }
    };
  },
  // computed: {
  //   //计算user对象
  //   personal_user() {
  //     return this.$store.state.user;
  //   },
  //   //计算gradeList对象
  //   personal_gradeList() {
  //     return this.$store.state.dict;
  //   }
  // },
  // watch: {
  //   //观察user对象
  //   personal_user(new_user, old_user) {
  //     if (new_user != null) {
  //       vm.init();
  //       console.log("AAAAAAAAAAAAAA");
  //     }
  //   },
  //   //观察gradeList对象
  //   personal_gradeList(new_gradeList, old_gradeList) {
  //     console.log(new_gradeList);
  //     if (new_gradeList != null) {
  //       vm.gradeList = new_gradeList["grade_mode"];
  //       console.log(vm.gradeList);
  //     }
  //   }
  // },
  methods: {
    changDate(val) {
      console.log(val);
      let selectTime = new Date(val.replace(/-/g,'/')).getTime();
      let currentTime = new Date().getTime();
      if (currentTime < selectTime) {
        vm.$message({
          showClose: true,
          message: "请选择正确的出生年月",
          type: "warning"
        });
        vm.personal_info.clueEntity.birthday = "";
      }
    },
    gotoChange() {
      router.push("/account/update_password");
    },
    //上传文件失败
    uploadError: function(response, file) {
      console.log("上传文件失败response" + response);
    },
    //回调成功
    handleAvatarSuccess(res, file) {
      if (res.status != "success") {
        this.$message.error("上传文件失败，错误码" + res.errorCode);
      } else {
        this.imgUrl = URL.createObjectURL(file.raw);
        this.personal_info.photo = res.data.url;
      }
      console.log(res);
      console.log(file);
    },
    //开始上传前
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG | PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    /**
     * 初始化
     */
    init() {
      console.log(vm.$store.state.user);
      vm.personal_info = tool.clone(vm.$store.state.user);
      vm.personal_info.clueEntity.grade =
        vm.personal_info.clueEntity.grade == 0
          ? ""
          : vm.personal_info.clueEntity.grade;
      //当前账户有收货地址时
      if (vm.personal_info.studentUserAddressEntityList.length > 0) {
        for (
          let i = 0;
          i < vm.personal_info.studentUserAddressEntityList.length;
          i++
        ) {
          let temp = vm.personal_info.studentUserAddressEntityList[i];
          temp.citys = [];
          temp.citys.push(temp.province, temp.city, temp.area);
        }
      } else {
        vm.isFirstAdd = true;
        //当前账户无收货地址时
        // vm.personal_info.studentUserAddressEntityList.push({
        //   receiverName: "",
        //   receiverPhone: "",
        //   province: "",
        //   city: "",
        //   area: "",
        //   address: "",
        //   isUse: "0",
        //   citys: []
        // });
      }
    },
    //保存
    submit() {
      let rules = [];
      let nickName = this.$refs.nickName;
      rules.push({
        judge: tool.judge("classname", vm.personal_info.clueEntity.realName),
        focus: nickName,
        tips: "请输入正确的姓名"
      });

      vm.personal_info.studentUserAddressEntityList.forEach(function(
        item,
        index
      ) {
        rules = rules.concat([
          {
            judge: tool.judge("name", item.receiverName),
            focus: vm.$refs[item.receiverName][0],
            tips: "请输入正确的收件人姓名"
          },
          {
            judge: tool.judge("phone", item.receiverPhone),
            focus: vm.$refs[item.receiverPhone][0],
            tips: "请输入正确的收件人号码"
          },
          {
            judge: item.address,
            focus: vm.$refs[item.address][0],
            tips: "请输入收货详细地址"
          }
        ]);
      });
      if (!tool.validate(rules)) {
        return;
      }
      if (vm.personal_info.studentUserAddressEntityList.length > 0) {
        let item = vm.personal_info.studentUserAddressEntityList.find(function(
          item
        ) {
          return item.isUse == "1";
        });
        if (item == undefined) {
          tool.message({
            showClose: true,
            message: "您没有设置默认收货地址！",
            type: "warning"
          });
          return;
        }
      }
      let paras = {
        nickName: vm.personal_info.clueEntity.realName,
        photo: vm.personal_info.photo,
        gender: vm.personal_info.clueEntity.gender,
        birthday: vm.personal_info.clueEntity.birthday,
        grade: vm.personal_info.clueEntity.grade,
        kindergarten: vm.personal_info.clueEntity.kindergarten,
        studentUserAddressVoList: []
      };
      for (
        let i = 0;
        i < vm.personal_info.studentUserAddressEntityList.length;
        i++
      ) {
        let temp = vm.personal_info.studentUserAddressEntityList[i];
        temp.province = temp.citys[0];
        temp.city = temp.citys[1];
        temp.area = temp.citys[2];
      }
      paras.studentUserAddressVoList =
        vm.personal_info.studentUserAddressEntityList;
      api.studentUserInfoUpdate(paras).then(function(data) {
        if (data.resultCode == 2000) {
          tool.message({
            showClose: true,
            message: "保存成功",
            type: "success"
          });
          //修改成功保存到状态中
          vm.$store.commit("setUser", tool.clone(vm.personal_info));
        } else {
          tool.message({
            showClose: true,
            message: data.message,
            type: "warning"
          });
          //修改失败重置用户信息
          // vm.personal_info = tool.clone(vm.$store.state.user);
        }
      });
    },
    /** 改变默认收货地址 */
    checkChange(item) {
      console.log(item);
      if (item.isUse == "1") {
        item.isUse = "0";
        console.log(item.isUse);
      } else {
        for (
          let i = 0;
          i < vm.personal_info.studentUserAddressEntityList.length;
          i++
        ) {
          let temp = vm.personal_info.studentUserAddressEntityList[i];
          temp.isUse = "0";
        }
        item.isUse = "1";
        console.log(item.isUse);
      }
    },
    /**
     * 删除收货地址
     */
    reduceAdress(item) {
      // if (vm.personal_info.studentUserAddressEntityList.length == 1) return;
      this.$confirm("此操作将删除该收货地址, 是否继续?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
        .then(() => {
          var index = vm.personal_info.studentUserAddressEntityList.indexOf(
            item
          );
          if (index !== -1) {
            vm.personal_info.studentUserAddressEntityList.splice(index, 1);
          }
        })
        .catch(() => {});
    },
    /**
     * 添加收货地址
     */
    addAdress() {
      if (vm.personal_info.studentUserAddressEntityList.length >= 10) return;
      vm.isFirstAdd = vm.personal_info.studentUserAddressEntityList.length == 0;
      vm.personal_info.studentUserAddressEntityList.push({
        receiverName: "",
        receiverPhone: "",
        province: "",
        city: "",
        area: "",
        address: "",
        isUse:
          vm.personal_info.studentUserAddressEntityList.length == 0 ? "1" : "0",
        citys: []
      });
    }
  },
  created: function() {
    vm = this;
    vm.citys = citys;
    let dicdata = vm.$store.state.dict;
    console.log(vm.personal_gradeList);
    // if (vm.personal_user == null) return;
    // if (vm.personal_gradeList == null) return;
    vm.gradeList = dicdata["grade_mode"]; //课程模式数据字典
    vm.init();
  }
};
</script>

<style lang="scss">
#personal_info {
  height: 100%;
  width: 100%;
  background: #ffffff;
  border-radius: 8px;
  margin-bottom: 0.2rem;
  .info_title {
    padding: 0.23rem 0.34rem 0.16rem;
    font-size: 0.2rem;
    color: #333333;
  }
  .line {
    width: 100%;
    height: 1px;
    background: #eeeeee;
  }
  .info_user {
    padding: 0.22rem 0.42rem;
    font-size: 0.16rem;
    color: #333333;
  }
  .info_user_name {
    margin: 0.14rem 0rem 0.1rem 0.58rem;
    font-size: 0.16rem;
    color: #999999;
  }
  .info_user_name span {
    margin-left: 0.4rem;
    font-size: 0.16rem;
    color: #333333;
  }
  .changePWD {
    margin: 0rem 0rem 0.24rem 0.58rem;
    font-size: 0.16rem;
  }
  .footer {
    width: 100%;
    text-align: center;
  }
  .ruleForm {
    margin-left: 0.63rem;
    .line1 {
      width: 90%;
      height: 1px;
      background: #eeeeee;
      margin-bottom: 0.1rem;
    }
    .el-input {
      font-size: 0.16rem;
    }
    .el-form-item {
      margin-bottom: 0.08rem;
    }
    .el-form-item__label {
      font-size: 0.16rem;
      color: #999999;
    }
    .el-form-item__content {
      font-size: 0.16rem;
      color: #666666;
    }
    .el-radio__label {
      font-size: 0.16rem;
      color: #666666;
    }
    .el-cascader__label {
      color: #666666;
      font-size: 0.16rem;
    }
    .stuheadimgbox {
      width: 1.16rem;
      height: 1.6rem;
      .headimg {
        width: 1.16rem;
        height: 1.16rem;
        border-radius: 4px;
        img {
          width: 100%;
          height: 1.16rem;
          border-radius: 4px;
        }
      }
      .uploadimg {
        width: 100%;
        height: 0.36rem;
        text-align: center;
        line-height: 0.36rem;
        margin-top: 0.04rem;
        .el-button {
          padding: 0.09rem 0.25rem;
          font-size: 0.16rem;
        }
      }
    }
    .add_btn,
    .reduce_btn {
      display: inline-block;
      vertical-align: middle;
      width: 0.3rem;
      height: 0.3rem;
      background-repeat: no-repeat;
      background-size: 0.2rem;
      background-position: center;
      cursor: pointer;
      user-select: none;
    }
    .add_btn {
      margin-left: 0.03rem;
      background-image: url(../../assets/img/person/person_add.png);
    }
    .reduce_btn {
      margin-left: 0.03rem;
      background-image: url(../../assets/img/person/person_close.png);
    }
    .el-checkbox {
      color: #666666;
      font-weight: 500;
      font-size: 0.16rem;
    }
  }
}
</style>